﻿using System;
using System.Text;
using System.Text.RegularExpressions;
using System.Data;
using System.Collections.Generic;
using Donal.Xms.Common;
using static System.Runtime.CompilerServices.RuntimeHelpers;
using System.Reflection;
using Newtonsoft.Json;

namespace Donal.Xms.BLL
{
    /// <summary>
    /// 手机短信
    /// </summary>
    public partial class sms_message
    {
        private readonly Model.sysconfig sysConfig = new BLL.sysconfig().loadConfig();//获得站点配置信息
        public sms_message()
        { }

        /// <summary>
        /// 检查账户信息是否正确
        /// </summary>
        /// <returns></returns>
        public bool Exists()
        {
            if (string.IsNullOrEmpty(sysConfig.smsapiurl) || (sysConfig.is_sms == 0) || string.IsNullOrEmpty(sysConfig.smssignName))
            {
                return false;
            }
            return true;
        }

        /// <summary>
        /// 发送手机短信
        /// </summary>
        /// <param name="mobiles">手机号码，以英文“,”逗号分隔开</param>
        /// <param name="smsTemplateCallindex">短信模板的调用别名</param>
        /// <param name="jsonParameter">如何有参数，请用Json格式 "{\"code\":\"" + strcode + "\"}"</param>
        /// <param name="msg">返回提示信息</param>
        /// <returns>bool</returns>
        public bool Send(string mobiles, string smsTemplateCallindex, string jsonParameter, out string msg)
        {
            //检查是否设置好短信账号
            if (!Exists())
            {
                msg = "短信配置参数有误，请完善后再提交！";
                return false;
            }
            //检查手机号码，如果超过2000则分批发送
            int sucCount = 0; //成功提交数量
            string errorMsg = string.Empty; //错误消息
            string[] oldMobileArr = mobiles.Split(',');
            int batch = oldMobileArr.Length / 2000 + 1; //2000条为一批，求出分多少批
            msg = errorMsg;

            for (int i = 0; i < batch; i++)
            {
                StringBuilder sb = new StringBuilder();
                int sendCount = 0; //发送数量
                int maxLenght = (i + 1) * 2000; //循环最大的数

                //检测号码，忽略不合格的，重新组合
                for (int j = 0; j < oldMobileArr.Length && j < maxLenght; j++)
                {
                    int arrNum = j + (i * 2000);
                    string pattern = @"^1\d{10}$";
                    string mobile = oldMobileArr[arrNum].Trim();
                    Regex r = new Regex(pattern, RegexOptions.IgnoreCase); //正则表达式实例，不区分大小写
                    Match m = r.Match(mobile); //搜索匹配项
                    if (m != null)
                    {
                        sendCount++;
                        sb.Append(mobile + ",");
                    }
                }

                //发送短信
                if (sb.ToString().Length > 0)
                {
                    try
                    {
                        Model.sms_template smsModel = new BLL.sms_template().GetModel(smsTemplateCallindex); //取得阿里短信Code
                        if (smsModel != null)
                        {
                            string AccessKeyId = DESEncrypt.Decrypt(sysConfig.AccessKeyId, sysConfig.sysencryptstring);
                            string AccessKeySecret = DESEncrypt.Decrypt(sysConfig.AccessKeySecret, sysConfig.sysencryptstring);

                            AlibabaCloud.OpenApiClient.Models.Config config = new AlibabaCloud.OpenApiClient.Models.Config
                            {
                                // 必填，您的 AccessKey ID
                                AccessKeyId = AccessKeyId,
                                // 必填，您的 AccessKey Secret
                                AccessKeySecret = AccessKeySecret,
                            };
                            // Endpoint 请参考 https://api.aliyun.com/product/Dysmsapi
                            config.Endpoint = sysConfig.smsapiurl;

                            AlibabaCloud.SDK.Dysmsapi20170525.Client client = new AlibabaCloud.SDK.Dysmsapi20170525.Client(config);
                            AlibabaCloud.SDK.Dysmsapi20170525.Models.SendSmsRequest sendSmsRequest = new AlibabaCloud.SDK.Dysmsapi20170525.Models.SendSmsRequest
                            {
                                SignName = sysConfig.smssignName,
                                TemplateCode = smsModel.content,
                                PhoneNumbers = mobiles,
                                TemplateParam = jsonParameter,
                            };
                            AlibabaCloud.TeaUtil.Models.RuntimeOptions runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
                            try
                            {
                                // 复制代码运行请自行打印 API 的返回值
                                AlibabaCloud.SDK.Dysmsapi20170525.Models.SendSmsResponse sendSmsResponse = client.SendSmsWithOptions(sendSmsRequest, runtime);

                                if (sendSmsResponse.Body.Code == sendSmsResponse.Body.Message && sendSmsResponse.Body.Code == "OK")
                                {
                                    sucCount++;
                                }
                                else
                                {
                                    msg = JsonConvert.SerializeObject(sendSmsResponse);
                                    Utils.WriteLogs("阿里短信发送异常", msg);
                                }
                            }
                            catch (Exception ex)
                            {
                                Utils.WriteLogs("阿里短信发送异常", ex.Message);
                                msg = "阿里短信发送异常：" + ex.Message;
                            }
                        }
                        else
                        {
                            msg = "发送失败，短信模板不存在，请联系管理员！";
                        }

                    }
                    catch (Exception ex)
                    {
                        Utils.WriteLogs("短信发送异常", ex.Message);
                        msg = "短信发送异常：" + ex.Message;
                    }
                }
            }

            //返回状态
            if (sucCount > 0)
            {
                msg = "发送成功！";
                return true;
            }
           
            return false;
        }

        /// <summary>
        /// 查询账户剩余短信数量
        /// </summary>
        public int GetAccountQuantity(out string code)
        {
            //检查是否设置好短信账号
            if (!Exists())
            {
                code = "115";
                return 0;
            }
            try
            {
                string result = Utils.HttpPost(sysConfig.smsapiurl, "ac=number&uid=" + sysConfig.AccessKeySecret + "&pwd=" + sysConfig.smspassword);

                smsNumber sn = JsonHelper.JSONToObject<smsNumber>(result);

                code = sn.stat;

                if (sn.stat == "100")
                {
                    return int.Parse(sn.number);
                }
                else
                {
                    code = sn.message;
                    return 0;
                }

            }
            catch
            {
                code = "115";
                return 0;
            }
        }

        /// <summary>
        /// 查询已发送数量
        /// </summary>
        public int GetSendQuantity(out string code)
        {
            //检查是否设置好短信账号
            if (!Exists())
            {
                code = "115";
                return 0;
            }
            try
            {
                string result = Utils.HttpPost(sysConfig.smsapiurl, "cmd=se&uid=" + sysConfig.AccessKeySecret + "&pwd=" + sysConfig.smspassword);
                string[] strArr = result.Split(new string[] { "||" }, StringSplitOptions.None);
                if (strArr[0] != "100")
                {
                    code = strArr[0];
                    return 0;
                }
                code = strArr[0];
                return Utils.StrToInt(strArr[1], 0);
            }
            catch
            {
                code = "115";
                return 0;
            }
        }

    }


    public class smsNumber
    {
        private string _stat = "";
        public string stat
        {
            set { _stat = value; }
            get { return _stat; }
        }

        private string _number = "";
        public string number
        {
            set { _number = value; }
            get { return _number; }
        }

        private string _message = "";
        public string message
        {
            set { _message = value; }
            get { return _message; }
        }
    }

    public class smsSend
    {
        private string _stat = "";
        public string stat
        {
            set { _stat = value; }
            get { return _stat; }
        }

        private string _message = "";
        public string message
        {
            set { _message = value; }
            get { return _message; }
        }
    }

}
